<template>
  <div class="migration-tool">
    <div class="config-section">
      <h2>数据库配置</h2>

      <div class="form-container">
        <div class="database-form">
          <h3>源数据库</h3>
          <el-form :model="sourceConfig" label-width="120px">
            <el-form-item label="历史配置">
              <el-select
                v-model="selectedSourceHistory"
                placeholder="选择历史源库配置"
                style="width: 100%"
                @change="onSelectHistory('source')"
                clearable
              >
                <el-option
                  v-for="(item, idx) in sourceHistoryList"
                  :key="idx"
                  :label="itemLabel(item)"
                  :value="idx"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="主机">
              <el-input v-model="sourceConfig.host" />
            </el-form-item>
            <el-form-item label="端口">
              <el-input v-model="sourceConfig.port" type="number" />
            </el-form-item>
            <el-form-item label="用户名">
              <el-input v-model="sourceConfig.user" />
            </el-form-item>
            <el-form-item label="密码">
              <el-input
                v-model="sourceConfig.password"
                type="password"
                show-password
              />
            </el-form-item>
            <el-form-item label="数据库名">
              <el-input v-model="sourceConfig.database" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="testConnection('source')">
                测试连接
              </el-button>
              <div class="test-result" :class="sourceTestResult.class">
                {{ sourceTestResult.message }}
              </div>
            </el-form-item>
          </el-form>
        </div>

        <div class="database-form">
          <h3>目标数据库</h3>
          <el-form :model="targetConfig" label-width="120px">
            <el-form-item label="历史配置">
              <el-select
                v-model="selectedTargetHistory"
                placeholder="选择历史目标库配置"
                style="width: 100%"
                @change="onSelectHistory('target')"
                clearable
              >
                <el-option
                  v-for="(item, idx) in targetHistoryList"
                  :key="idx"
                  :label="itemLabel(item)"
                  :value="idx"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="主机">
              <el-input v-model="targetConfig.host" />
            </el-form-item>
            <el-form-item label="端口">
              <el-input v-model="targetConfig.port" type="number" />
            </el-form-item>
            <el-form-item label="用户名">
              <el-input v-model="targetConfig.user" />
            </el-form-item>
            <el-form-item label="密码">
              <el-input
                v-model="targetConfig.password"
                type="password"
                show-password
              />
            </el-form-item>
            <el-form-item label="数据库名">
              <el-input v-model="targetConfig.database" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="testConnection('target')">
                测试连接
              </el-button>
              <div class="test-result" :class="targetTestResult.class">
                {{ targetTestResult.message }}
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <div class="form-actions">
        <el-button type="primary" @click="saveConfig">保存配置</el-button>
        <el-button @click="loadDefaultConfig">加载默认配置</el-button>
      </div>
    </div>

    <!-- @latest-sql-log="(logObj) => emit('latest-sql-log', logObj)" -->
    <SingleTableMigration :tableList="tableList" :isConfigValid="isConfigValid">
    </SingleTableMigration>

    <div class="migration-section">
      <h2>多表批量迁移</h2>
      <el-form label-width="140px">
        <el-form-item label="选择表名(可多选)">
          <el-select
            v-model="selectedTables"
            multiple
            placeholder="请选择要批量迁移的表"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="table in tableList"
              :key="table"
              :label="table.Name + ' - ' + table.Description"
              :value="table.Name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否覆盖">
          <el-switch
            v-model="batchMigrationSettings.removeField"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>
        <el-form-item label="是否删除多余字段">
          <el-switch
            v-model="batchMigrationSettings.isDeleteRedundant"
            active-text="是"
            inactive-text="否"
          />
          <div class="hint">
            如果目标表中存在源表没有的字段，是否删除这些字段
          </div>
        </el-form-item>
      </el-form>
      <div class="migration-controls">
        <el-button
          type="primary"
          @click="startBatchMigration"
          :disabled="
            isMigrating || !isConfigValid || selectedTables.length === 0
          "
          >批量迁移</el-button
        >
      </div>
      <div v-if="batchMigrationResult" class="migration-result">
        <h3>批量迁移结果</h3>
        <ul>
          <li
            v-for="item in batchMigrationResult.results"
            :key="item.tableName"
          >
            <span :style="{ color: item.success ? '#27ae60' : '#e74c3c' }"
              >{{ item.tableName }}：</span
            >
            <span>{{ item.success ? "成功" : "失败" }}</span>
            <span v-if="item.message"> - {{ item.message }}</span>
          </li>
        </ul>
      </div>
    </div>

    <ApiEngineMigration ref="apiEngineMigrationRef" />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import migrationApi from "../api/migrationApi";
import SingleTableMigration from "./SingleTableMigration.vue";
import ApiEngineMigration from "./ApiEngineMigration.vue";

// 新增ref
const apiEngineMigrationRef = ref(null);

// 配置数据
const sourceConfig = reactive({
  host: "",
  port: "",
  user: "",
  password: "",
  database: "",
});

const targetConfig = reactive({
  host: "",
  port: "",
  user: "",
  password: "",
  database: "",
});

// 历史配置相关
const sourceHistoryList = ref([]);
const targetHistoryList = ref([]);
const selectedSourceHistory = ref(null);
const selectedTargetHistory = ref(null);

function itemLabel(item) {
  return `${item.host}:${item.port} - ${item.user}@${item.database}`;
}

function loadHistory() {
  sourceHistoryList.value = JSON.parse(
    localStorage.getItem("db_source_history") || "[]"
  );
  targetHistoryList.value = JSON.parse(
    localStorage.getItem("db_target_history") || "[]"
  );
}

function saveHistory(type, config) {
  const key = type === "source" ? "db_source_history" : "db_target_history";
  let list = JSON.parse(localStorage.getItem(key) || "[]");
  // 去重：只保留不同host/port/user/database的配置
  if (
    !list.some(
      (item) =>
        item.host === config.host &&
        item.port === config.port &&
        item.user === config.user &&
        item.database === config.database
    )
  ) {
    list.unshift({ ...config });
    // 最多保存10条
    if (list.length > 10) list = list.slice(0, 10);
    localStorage.setItem(key, JSON.stringify(list));
  }
  // 重新加载
  loadHistory();
}

function onSelectHistory(type) {
  console.log(type, "type", selectedSourceHistory.value);
  // 如果清空了配置
  if (type === "source" && selectedSourceHistory.value === undefined) {
    Object.assign(sourceConfig, {
      host: "",
      port: "",
      user: "",
      password: "",
      database: "",
    });
    return;
  }
  if (type === "target" && selectedTargetHistory.value === undefined) {
    Object.assign(targetConfig, {
      host: "",
      port: "",
      user: "",
      password: "",
      database: "",
    });
    return;
  }
  if (type === "source" && selectedSourceHistory.value !== null) {
    const item = sourceHistoryList.value[selectedSourceHistory.value];
    if (item) Object.assign(sourceConfig, item);
  }
  if (type === "target" && selectedTargetHistory.value !== null) {
    const item = targetHistoryList.value[selectedTargetHistory.value];
    if (item) Object.assign(targetConfig, item);
  }
}

// 测试结果
const sourceTestResult = reactive({
  message: "",
  class: "",
});

const targetTestResult = reactive({
  message: "",
  class: "",
});

// 迁移设置
// 多表迁移设置
const batchMigrationSettings = reactive({
  removeField: false,
  isDeleteRedundant: false,
});
const selectedTables = ref([]);
const batchMigrationResult = ref(null);

// 迁移状态
const isMigrating = ref(false);
const migrationProgress = ref(0);
const currentPage = ref(0);
const totalPages = ref(0);
const migratedCount = ref(0);
const skippedCount = ref(0);
const migrationResult = ref(null);

// 表格数据
const tableList = ref([]);

// 计算属性
const progressStatus = computed(() => {
  if (migrationProgress.value === 100) return "success";
  return migrationProgress.value < 30 ? "exception" : "primary";
});

const isConfigValid = computed(() => {
  return (
    sourceConfig.host &&
    sourceConfig.user &&
    sourceConfig.database &&
    targetConfig.host &&
    targetConfig.user &&
    targetConfig.database
  );
});

// 生命周期钩子
onMounted(async () => {
  // await loadConfig();
  loadHistory();
});

// 方法
async function loadConfig() {
  try {
    const response = await migrationApi.getConfig();
    if (response.data.success) {
      const config = response.data.config;
      Object.assign(sourceConfig, config.source);
      Object.assign(targetConfig, config.target);
      ElMessage.success("配置加载成功");
    }
  } catch (error) {
    ElMessage.error(`配置加载失败: ${error.message}`);
  }
}

async function saveConfig() {
  try {
    const response = await migrationApi.saveConfig({
      source: sourceConfig,
      target: targetConfig,
    });

    if (response.data.success) {
      ElMessage.success(response.data.message);
    }
  } catch (error) {
    ElMessage.error(`配置保存失败: ${error.message}`);
  }
}

async function testConnection(type) {
  const config = type === "source" ? sourceConfig : targetConfig;
  const result = type === "source" ? sourceTestResult : targetTestResult;

  try {
    const response = await migrationApi.testConnection({
      type,
      ...config,
    });

    if (response.data.success) {
      result.message = response.data.message;
      result.class = "success";
      saveHistory(type, config);

      // 连接源库成功后，刷新接口列表
      if (type === "source" && apiEngineMigrationRef.value) {
        apiEngineMigrationRef.value.fetchApiNames();
      }
    } else {
      result.message = response.data.message;
      result.class = "error";
    }
  } catch (error) {
    result.message = `测试失败: ${error.message}`;
    result.class = "error";
  }

  if (type === "source") {
    migrationApi
      .getTables(sourceConfig)
      .then((response) => {
        if (response.data.success) {
          tableList.value = response.data.tables;
        } else {
          ElMessage.error(`获取表列表失败: ${response.data.message}`);
        }
      })
      .catch((error) => {
        ElMessage.error(`获取表列表失败: ${error.message}`);
      });
  }
}

function loadDefaultConfig() {
  Object.assign(sourceConfig, {
    host: "localhost",
    port: 3306,
    user: "root",
    password: "",
    database: "source_db",
  });

  Object.assign(targetConfig, {
    host: "localhost",
    port: 3306,
    user: "root",
    password: "",
    database: "target_db",
  });

  ElMessage.info("已加载默认配置");
}

const emit = defineEmits(["show-logs", "latest-sql-log"]);

// 多表批量迁移
async function startBatchMigration() {
  if (!isConfigValid.value) {
    ElMessage.warning("请先配置数据库连接");
    return;
  }
  if (selectedTables.value.length === 0) {
    ElMessage.warning("请选择要批量迁移的表");
    return;
  }
  isMigrating.value = true;
  batchMigrationResult.value = null;
  try {
    const response = await migrationApi.batchMigration({
      tableNames: selectedTables.value,
      removeField: batchMigrationSettings.removeField,
      isDeleteRedundant: batchMigrationSettings.isDeleteRedundant,
    });
    if (response.data) {
      batchMigrationResult.value = response.data;
    }
  } catch (error) {
    ElMessage.error(`批量迁移失败: ${error.message}`);
  } finally {
    isMigrating.value = false;
  }
}
</script>

<style scoped>
.migration-tool {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 25px;
  flex: 1;
}

.config-section h2,
.migration-section h2 {
  color: #2c3e50;
  border-bottom: 2px solid #3498db;
  padding-bottom: 10px;
  margin-bottom: 20px;
}

.form-container {
  display: flex;
  gap: 30px;
  margin-bottom: 20px;
}

.database-form {
  flex: 1;
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 6px;
  border: 1px solid #eaeaea;
}

.database-form h3 {
  margin-top: 0;
  color: #3498db;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 20px;
}

.test-result {
  margin-top: 10px;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 14px;
}

.test-result.success {
  background-color: rgba(46, 204, 113, 0.2);
  color: #27ae60;
  border: 1px solid #27ae60;
}

.test-result.error {
  background-color: rgba(231, 76, 60, 0.2);
  color: #e74c3c;
  border: 1px solid #e74c3c;
}

.migration-section {
  margin-top: 30px;
}

.migration-controls {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 6px;
  border: 1px solid #eaeaea;
}

.hint {
  font-size: 12px;
  color: #7f8c8d;
  margin-top: 5px;
}

.migration-progress {
  margin-top: 25px;
}

.progress-container {
  margin-top: 15px;
}

.progress-details {
  margin-top: 15px;
  padding: 15px;
  background-color: #ecf0f1;
  border-radius: 6px;
  font-size: 14px;
}

.migration-result {
  margin-top: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #eaeaea;
}

.result-summary {
  display: flex;
  gap: 20px;
  margin: 15px 0;
  font-size: 16px;
}

.result-summary .success {
  color: #27ae60;
  font-weight: 500;
}

.result-summary .skipped {
  color: #f39c12;
  font-weight: 500;
}

.error-section {
  margin-top: 20px;
}

.error-list {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 10px;
}

.error-item {
  padding: 8px 10px;
  border-bottom: 1px solid #f0f0f0;
  font-size: 13px;
}

.error-item:last-child {
  border-bottom: none;
}

.error-id {
  display: inline-block;
  min-width: 100px;
  font-weight: 500;
  color: #e74c3c;
}

.error-message {
  color: #7f8c8d;
}
</style>
